package com.jiepu.daily.corejava.advanceed.part6thread.producerandconsumer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author: xinjie.txt
 * @date: 2020/8/3  10:35
 */
public class ProducerThread extends Thread {

	// 仓库
	List<Object> list = new ArrayList<>();

	int count = 0;

	public ProducerThread() {

	}

	// 生产制造
	public void produce() {
		Object product = new Object();
		list.add(product);

		System.out.println("produce product num:" + ++count);
	}

	// 生产*100
	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			produce();


		}
	}


	static class ConsumerThread extends Thread {
		Object o;
		int count = 0;
		ProducerThread p;

		public ConsumerThread(ProducerThread p, Object o) {
			this.p = p;
			this.o = o;
		}

		// 买
		public void buy() {
			synchronized (o) {

				p.list.remove(o);
				System.out.println("Consumer buy" + ++count);
			}

		}

		// 买*100
		@Override
		public void run() {
			try {
				p.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			for (int i = 0; i < 100; i++) {
				buy();
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

	}


	public static void main(String[] args) {
		Object lock = null;

		ProducerThread producerThread = new ProducerThread();
		producerThread.start();
		ConsumerThread consumerThread = new ConsumerThread(producerThread, lock);
		consumerThread.start();




	}

}
